package com.open.cloud.rbac.jwt;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Component
@Slf4j
public class TokenSSOProvider {

    private String secret = "IUkVLcM72OGEOJgQX3BXjLP4dsLs084joI2aQWcmB8rLxPyEX2cxLdVllRrx/v/Tzh2iSPsftmcABQ+q5kVYdQ==";

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
    private SecretKeySpec signingKey = null;
    private static final String TOKEN_PREFIX = "Bearer ";

    @Value("${user.token.renewal}")
    private Long renewalTime;

    @PostConstruct
    public void init() {
        byte[] secretB = secret.getBytes(StandardCharsets.UTF_8); //加密秘钥
        String algorithm = "hs512";
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(algorithm);
        this.signingKey = new SecretKeySpec(Base64.decodeBase64(secretB), signatureAlgorithm.getJcaName());
    }


    public TokenResponse createToken(JwtAccessToken jwtAccessToken, long TTLMills, Map<String, Object> params) {
        TokenResponse tokenResponse = new TokenResponse();
        Map<String, Object> claims = new HashMap<>();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        claims.put(Claims.ID, "1.0");
        claims.put(Claims.ISSUER, jwtAccessToken.getIss());
        claims.put(Claims.SUBJECT, "Inspur-Auth-Manager");
        claims.put(Claims.AUDIENCE, jwtAccessToken.getSub());
        if (params != null) {
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                claims.put(key, params.get(key));
            }
        }

        JwtBuilder jwtBuilder = Jwts.builder().setClaims(claims);
        if (TTLMills >= 0) {
            long expMills = nowMillis + TTLMills;
            Date exp = new Date(expMills);
            jwtBuilder.setExpiration(exp).setNotBefore(now);
            tokenResponse.setExpTime(DateFormatUtils.format(exp, "yyyy-MM-dd HH:mm:ss"));
        }
        byte[] secretB = secret.getBytes(StandardCharsets.UTF_8); //加密秘钥
        String algorithm = "hs512";
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(algorithm);
        this.signingKey = new SecretKeySpec(Base64.decodeBase64(secretB), signatureAlgorithm.getJcaName());

        jwtBuilder.signWith(signingKey, signatureAlgorithm);
        String token = jwtBuilder.compact();
        tokenResponse.setAccessToken(token);
        tokenResponse.setRenewal(TTLMills);
        if (TTLMills >= 0) {
            long expMills = nowMillis + TTLMills + 10000000L;
            Date exp = new Date(expMills);
            jwtBuilder.setExpiration(exp).setNotBefore(now);
        }
        jwtBuilder.signWith(signingKey, signatureAlgorithm);
        String refreshToken = jwtBuilder.compact();
        tokenResponse.setRefreshToken(refreshToken);
        return tokenResponse;
    }

    public Claims parseToken(String jsonWebToken) {
        String resolveToken = resolveToken(jsonWebToken);
        Claims claims = null;
        try {
            claims = Jwts.parserBuilder().setAllowedClockSkewSeconds(60).setSigningKey(signingKey).build()
                    .parseClaimsJws(resolveToken).getBody();
        } catch (ExpiredJwtException ex) {
//            log.error("登录凭证已经过期", ex);
            log.error("登录凭证已经过期");
//            throw new AuthException("登录凭证已经过期");
        } catch (Exception ex) {
//            log.error("登录凭证不合法", ex);
            log.error("登录凭证不合法");
//            throw new AuthException("登录凭证不合法");
        }
        return claims;
    }

    /**
     * 获取JWT令牌
     *
     * @param token
     * @return
     */
    private String resolveToken(String token) {
        if (StringUtils.isNotEmpty(token)) {
            if (token.startsWith(TOKEN_PREFIX)) {
                return token.substring(7);
            } else {
                // 如果token不以BEARER_STARTSTR，直接返回，兼容权限系统
                return token;
            }
        }
        return null;
    }


    public static void main(String[] args) {
        JwtAccessToken jwtAccessToken = new JwtAccessToken();
        jwtAccessToken.setIss("Inspur");
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.LOGIN_USER_ID, "1");
        params.put(Constants.LOGIN_ACCOUNT_ID, "1");
        params.put(Constants.LOGIN_USER_NAME, "test");
        params.put(Constants.LOGIN_ACCOUNT_NAME, "admin");
        params.put(Constants.LOGIN_LOGINNAME, "admin");
        long expiredTime = 2022386666000L;
        TokenSSOProvider provider=new TokenSSOProvider();
        TokenResponse token = provider.createToken(jwtAccessToken, expiredTime, params);
        System.out.println(token);
    }

}
